import React from 'react';
import { Spin, notification, message,Tabs } from 'antd';

import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
import SiderMenu from '@/components/SiderMenu';
import Authorized from '@/utils/Authorized';
import Footer from './Footer';
import pathToRegexp from 'path-to-regexp';
import GlobalHeader from './Header';
import router from 'umi/router';
import Context from './MenuContext';
import { getAuthorityRouters, getAllRouters, getSystemRouters, getAllMenus } from '@/utils/utils';
import Exception403 from '../pages/system/exception/403';
import layoutConfig from '../../config/layout.config';
import ErrorBoundary from '@/components/error/ErrorBoundary';
import '../global.less';
import styles from './Basic.less';
//import 'zent/css/index.css';
import { Icon } from 'zent';
import { urlToList } from '../components/_utils/pathTools';

const TabPane=Tabs.TabPane;
function formatter(data, parentPath = '', parentAuthority, parentName) {
  return data.map(item => {
    let locale = 'menu';
    if (parentName && item.name) {
      locale = `${parentName}.${item.name}`;
    } else if (item.name) {
      locale = `menu.${item.name}`;
    } else if (parentName) {
      locale = parentName;
    }
    const result = {
      ...item,
      locale,
      authority: item.authority || parentAuthority,
    };
    if (item.routes) {
      const children = formatter(item.routes, `${parentPath}${item.path}/`, item.authority, locale);
      // Reduce memory usage
      result.children = children;
    }
    delete result.routes;
    return result;
  });
}


const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
  },
};
@connect(({ global, loading }) => ({
  loading: loading.effects['global/getConfigApp'],
  menus: global.menuData,
  menuData: global.menuData,
  cdnUrl: global.oemInfo.cdnUrl,
  storeLogo: global.oemInfo.storeLogo,
  storeName: global.oemInfo.storeName,
  icoPath: global.oemInfo.icoPath,
  showTop: global.showTop,
  topChildren: global.topChildren
}))


export default class BasicLayout extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      rendering: true,
      isMobile: false,
      menuData: [],
      showTop: true,
      loading: true,
      load: true,
      hasError: false,
    };
    this.flatMenuKeys = this.getFlatMenuKeys(props.menuData);
  }

  componentWillMount() {
    const { dispatch, route: { routes }, location: { pathname } } = this.props;
    let systemRouters = getSystemRouters(routes);
    let isExist = false; //判断路由是否在系统路由存在
    if (/^\d{12}$/.test(this.props.match.params.storeId)) {
      window.storeId = this.props.match.params.storeId;
      systemRouters.forEach(item => {
        let result = pathToRegexp(item).exec(pathname);
        if (result) {
          isExist = true;
        }
      })

      if (!isExist) {
        router.replace({
          pathname: `/exception/404`,
        });
        return false;
      }      
      dispatch({
        type: 'global/getConfigApp',
        callback: {
          success:(data) => {
            window.cdnUrl = data.oemInfo.cdnUrl;
            this.setState({
              loading: false
            })
          },
          error:(data)=>{
            message.error(data.Msg)
          }
        }
      });
    }
  }
  componentDidMount() {
    const { location: { pathname } } = this.props;
    let dom = document.querySelector(`#layoutRight`);
    const that=this;
    window.addEventListener('resize', function () {
      let winHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
      let winWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidht;
      if (winWidth < 1440) {
        //document.querySelector(`#layoutRight`).classList.add(`${styles.layoutRight_none}`);
        // document.querySelector(`#layoutContent`).classList.add(`${styles.mr0}`);
        if (pathname !== `/${window.storeId}/mall/dashboard`) {
          if (dom&&dom.classList.contains(`${styles.layoutRight_show}`)) {
            dom.classList.remove(`${styles.layoutRight_show}`);
          }
        }
      } else {
        //document.querySelector(`#layoutRight`).classList.remove(`${styles.layoutRight_none}`);
        //document.querySelector(`#layoutRight`).classList.add(`${styles.layoutRight_show}`);
        //document.querySelector(`#layoutContent`).classList.remove(`${styles.mr0}`);
      }
    })
    window.addEventListener('hashchange', function () {
      window.scrollTo(0, 0);
      if(/^\d{12}$/.test(that.props.match.params.storeId)){
        if(that.props.location.pathname===`/${that.props.match.params.storeId}/`||that.props.location.pathname===`/${that.props.match.params.storeId}`){
          router.replace({
            pathname: `/${that.props.match.params.storeId}/dashboard`,
          });
        }
      }
    })
  }
  getMenuData() {
    const {
      route: { routes },
    } = this.props;
    return formatter(routes);
  }

  getPageTitle = pathname => {
    const { icoPath, storeName, storeLogo, cdnUrl, menuData } = this.props;
    var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
    link.type = 'image/gif, image/jpeg, image/png, image/x-icon';
    link.rel = 'shortcut icon';
    // link.href='https://xkdsaas.oss-cn-shanghai.aliyuncs.com/system/oem/oem0/favicon.ico';
    //    console.log(icoPath)
    link.href = icoPath;
    //link.href=`${cdnUrl}/${storeLogo}`;
    document.getElementsByTagName('head')[0].appendChild(link);
    let routes = this.getMenuData();
    let pagename = '概况';
    for (let i = 0; i < routes.length; i++) {
      let item = routes[i];
      if (item.children && item.children.length) {
        for (let j = 0; j < item.children.length; j++) {
          let v = item.children[j];
          if (v.path && pathToRegexp(v.path).exec(pathname)) {
            if (pathname === pathToRegexp(v.path).exec(pathname)[0]) {
              pagename = v.name;
            }
          }
        }
      }
    }
    return `${storeName ? `${pagename}` + ' - ' + storeName : ''}`;
  };

  getFlatMenuKeys(menus) {
    let keys = [];
    menus.forEach(item => {
      if (item.children) {
        keys = keys.concat(this.getFlatMenuKeys(item.children));
      }
      keys.push(item.path);
    });
    return keys;
  }

  getSelectedMenuKeys = () => {
    const {
      location: { pathname },
    } = this.props;
    return urlToList(pathname).map(itemPath => getMenuMatches(this.flatMenuKeys, itemPath).pop());
  };

  getLayoutStyle = () => {
    const { isMobile } = this.state;
    const { fixSiderbar, collapsed, layout } = this.props;
    if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
      return {
        paddingLeft: collapsed ? '80px' : '256px',
      };
    }
    return null;
  };

  getContentStyle = () => {
    const { fixedHeader, location: { pathname } } = this.props;
    return {
      margin: '16px 16px 0',
      marginRight: pathname === `/${window.storeId}/mall/dashboard` ? 16 : 200,
      paddingTop: fixedHeader ? 64 : 0,
      paddingBottom: this.getFooterLayout() ? 80 : 0,
      minHeight: '77vh'
    };
  };
  toggle = () => {
    document.querySelector(`#layoutRight`).classList.add(`${styles.layoutRight_show}`);
  }
  close = () => {
    document.querySelector(`#layoutRight`).classList.remove(`${styles.layoutRight_show}`);
  }
  getTopLayout = () => {
    let config = layoutConfig.hideTop;
    const { location: { pathname } } = this.props;
    // let index = config.findIndex((item) => pathname === `/${window.storeId}${item}`);
    // if (index > -1) {
    //   return true;
    // } else {
    //   return false;
    // }
    for (let i = 0; i < config.length; i++) {
      if (pathToRegexp(config[i]).exec(pathname)) {
        if (pathname === pathToRegexp(config[i]).exec(pathname)[0]) {
          return true
        }
      }
    }
    return false;
  }
  getFooterLayout = () => {
    let config = layoutConfig.hideFooter;
    const { location: { pathname } } = this.props;
    //let index = config.findIndex((item) => pathname === `/${window.storeId}${item}`);
    for (let i = 0; i < config.length; i++) {
      if (pathToRegexp(config[i]).exec(pathname)) {
        if (pathname === pathToRegexp(config[i]).exec(pathname)[0]) {
          return true
        }
      }
    }
    return false;
    // if (index > -1) {
    //   return true;
    // } else {
    //   return false;
    // }
  }
  getMenuLayout = () => {
    let config = layoutConfig.hideMenu;
    const { location: { pathname } } = this.props;
    // let index = config.findIndex((item) => pathname === `/${window.storeId}${item}`);
    // if (index > -1) {
    //   return true;
    // } else {
    //   return false;
    // }
    for (let i = 0; i < config.length; i++) {
      if (pathToRegexp(config[i]).exec(pathname)) {
        if (pathname === pathToRegexp(config[i]).exec(pathname)[0]) {
          return true
        }
      }
    }
    return false;
  }

  reload = () => {
    this.setState({
      load: false
    }, () => {
      this.setState({
        load: true
      })
    })
  }

  render() {
    const {
      children,
      location: { pathname },
      menus,
      showTop,
      route: { routes },
      topChildren,
      //loading
    } = this.props;
    const { loading, load, hasError } = this.state;

    const layout = (
      <Spin spinning={loading}>
        {
          loading?<div style={{height:220}}></div>:(
            <div style={{ position: 'relative', minHeight: '100vh', flexDirection: 'row', display: "flex", flex: "auto", background: "#f0f2f5", boxSizing: "border-box" }}>
            <SiderMenu {...this.props} reload={this.reload} />
            <div
              style={{
                // ...this.getLayoutStyle(),
                flexDirection: 'column',
                display: "flex",
                flex: "auto",
                background: "#f0f2f5",
                boxSizing: "border-box",
                minHeight: '100vh',
                marginLeft: pathname === `/${window.storeId}/mall/dashboard` ? 72 : 184,
                // marginRight:184,
                minWidth: "1040px"
              }}
            >              
              {/* {this.getTopLayout() ? null : <GlobalHeader {...this.props} toggle={this.toggle} topChildren={topChildren} />} */}
              <GlobalHeader {...this.props} toggle={this.toggle} topChildren={topChildren} />
              <div style={this.getContentStyle()} className={styles.layoutContent}>
                <ErrorBoundary currentRouter={this.props.location.pathname}>
                  <Authorized
                    AuthorityRouters={getAllMenus(menus, this.props.match.params.storeId)}
                    allRouters={getSystemRouters(routes)}  //获取所有路由
                    currentRouter={this.props.location.pathname}
                    noMatch={<Exception403 />}
                  >
                    {
                      load ?
                        children
                        : null
                    }
                  </Authorized>
                </ErrorBoundary>
              </div>
  
              {
                this.getFooterLayout() ? null :
                  <Footer />
              }
              {/* <div className={styles.bottomOpration}></div>           */}
            </div>
            {
              this.getTopLayout() ? null :
                <div
                  className={styles.layoutRight}
                  id="layoutRight"
                >
                  <div className={styles.help}>
                    帮助和服务
               <Icon type="close" className={styles.close} onClick={this.close} />
                  </div>
                </div>
            }
          </div>
          )
        }       
      </Spin>
    );

    return (
      <React.Fragment>
        <DocumentTitle title={this.getPageTitle(pathname)}>
          <ContainerQuery query={query}>
            {params => (
              <Context.Provider>
                <div className={classNames(params)}>{layout}</div>
              </Context.Provider>
            )}
          </ContainerQuery>
        </DocumentTitle>
      </React.Fragment>
    );
  }
}

function getMenuMatches(flatMenuKeys, path) {
  return flatMenuKeys.filter(item => item && pathToRegexp(item).test(path));
}
